package com.ayu.springsecuritylearn.config;

import com.ayu.springsecuritylearn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Author: 徐林玉//作者及
 * @Date: 2021/9/26//完成日期
 * @Description: //
 * @Version: v0.0.1 // 版本信息
 * @Function List: // 主要函数及其功能
 * @Others: // 其它内容的说明
 * @History: // 历史修改记录
 **/

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{

	@Autowired
	private UserService userService;

	@Bean
	public BCryptPasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}

	//指定认证对象的来源
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {

//		auth.inMemoryAuthentication().withUser("user").password("{noop}123").roles("USER");

		auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
	}



	//SpringSecurity配置信息
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll()
				.antMatchers("/product").hasAnyRole("USER","ADMIN")
				.anyRequest().authenticated()
				.and()
				.formLogin()
				.loginPage("/login.jsp")
				.loginProcessingUrl("/login")
				.successForwardUrl("/index.jsp")
				.failureForwardUrl("/failer.jsp")
				.and()
				.logout()
				.logoutSuccessUrl("/logout")
				.invalidateHttpSession(true)
				.logoutSuccessUrl("/login.jsp")
				.and()
				.csrf()
				.disable();
	}
}